export function BMapInit() {
  return new Promise((resolve) => {
    // 如果已加载直接返回
    if (typeof BMap !== 'undefined') {
      resolve(BMap)
      return true
    }
    // 百度地图异步加载回调处理
    window.bMapInit = function () {
      // console.log("百度地图脚本初始化成功...");
      resolve(BMap)
    }

    // 插入script脚本
    let scriptNode = document.createElement('script')
    scriptNode.src =
      '//api.map.baidu.com/api?v=2.0&ak=PGVEIMhlnUlFAY4GQEEiXI2aBnucMmGL&callback=bMapInit'
    document.body.appendChild(scriptNode)
  })
}

export function getCurPosition(BMap) {
  return new Promise((resolve) => {
    var geolocation = new BMap.Geolocation()
    // 开启SDK辅助定位
    geolocation.enableSDKLocation()
    geolocation.getCurrentPosition(function (r) {
      if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        // console.log(r)
        // alert('您的位置：' + r.point.lng + ',' + r.point.lat)
        resolve({ lon: r.longitude, lat: r.latitude })
      } else {
        // alert('failed' + this.getStatus())
        resolve(null)
      }
    })
  })
}

// 调用 return的距离单位为km
export function getDistance(lat1, lng1, lat2, lng2) {
  var radLat1 = (lat1 * Math.PI) / 180.0
  var radLat2 = (lat2 * Math.PI) / 180.0
  var a = radLat1 - radLat2
  var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0
  var s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    )
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000
  return s
}
